import React, { memo, Component } from 'react'
import { getThingDetail,sendAnswers } from '@/api/user'
import { Spin, Form, Image, Modal,Input, Button, message } from 'antd'
import './index.css'
import TurnBack from '../../components/pageComponents/turnBack'
import { getParam, formatDate, getDateDiff } from '../../utils/tool'
import { baseUrl } from '../../assets/baseUrl'
const BaseUrl = baseUrl()
// import { NotificationOutlined } from '@ant-design/icons';
class thingDetail extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            type:null,
            numberId: getParam(this.props.location.search, 'numberId'),
            connectMine:getParam(this.props.location.search, 'connectMine'),  //设置返回上一页用的
            detail: null,  //详情
            previewVisible: false,
            previewImage: null,
            imgs: [],//图片列表
            backUrl: null, //返回上一页url
            questions:[],//认领问题
            answers:[],//认领答案
            hasAnswered:false, //是否已回答过问题
        }
    }
    componentDidMount() {
        getThingDetail({ numberId: this.state.numberId }).then(res => {
            if(res.data?.data[0]?.found){
                if(res.data?.data[0]?.forPeople)
                Modal.success({
                    content: '本条失物招领已成功找到失主，非常感谢您的持续关注，uooKi官方向每位助力的小伙伴报以最真挚的感激~比心',
                });
                else{
                    Modal.success({
                        content: '本条寻物启事已成功找到失物，非常感谢您的持续关注，uooKi官方向每位助力的小伙伴报以最真挚的感激~比心',
                    });
                }
            }
            let {connectMine} = this.state
            let detail = res.data?.data[0]
            let imgs = detail.thingImg?.split('&')
            imgs?.map((item, index) => {
                if (item == '')
                    imgs.splice(index, 1)
            })
            let backUrl = null
            if(connectMine)
                backUrl = '/home/schoolIndex/thingLost?type=3'
            else if (detail.forPeople == 1)
                backUrl = '/home/schoolIndex/thingLost?type=1'
            else
                backUrl = '/home/schoolIndex/thingLost?type=2'

            let questions = detail.questions?.split('QUE')
            let answers = []
            if(res.data?.answers[0]?.answers){
                answers = res.data?.answers[0]?.answers.split('ANS')
                this.setState({
                    hasAnswered:true
                })
            }
            else {
                questions?.map((item)=>{
                    answers.push('')
                })
            }
            let type = detail.forPeople == 1 ? 1 : 2
            this.setState({
                detail,
                imgs,
                backUrl,
                questions,
                answers,
                type
            })
        })
    }

    //点击认领按钮触发
    createOrder=()=>{
        let {answers,questions,detail} = this.state
        let allRight = true
        answers.map((item,index)=>{
            if(item == ''){
                message.error(`请输入第${index+1}个认领问题的答案`)
                allRight=false
            }
        })
        if(allRight){
            let ans = answers.join('ANS')
            let data = {
                firstTime:detail.createTime,
                thingImg:detail.thingImg,
                tag:detail.tag,
                content:detail.content,
                answers:ans,
                questions:questions.join('QUE'),
                senderId:detail.senderId,
                createTime:Date.parse(new Date()),
                numberId:detail.numberId
            }
            sendAnswers(data).then(res=>{
                if(res.data?.code == 200){
                    message.success({content:res.data?.message,duration:5})
                    this.setState({
                        hasAnswered:true
                    })
                }
                else{
                    message.warning(res.data?.message)
                }
            })
        }
    }
    render() {
        const { detail, previewVisible, previewImage, imgs,questions,type,hasAnswered } = this.state
        return (
            <Spin spinning={this.state.loading} size="large">
                <div style={{ height: '92vh', background: 'rgba(255,255,255,.4)' }}>
                    <div style={{ paddingTop: '5vh' }}>
                        <TurnBack url={this.state.backUrl} />
                    </div>
                    <div className='flex' style={{marginTop:24}}>
                        <div style={{ 
                            padding: '30px 0 30px 48px', 
                            width: '45vw',
                            backgroundColor:'rgba(255,255,255,.5)',
                            borderRadius:16,
                            marginLeft:'3%',
                            boxShadow:'1px 1px 5px rgb(129,129,129)'
                        }}
                        >
                            <ul className='detail-ui'>
                                <li>
                                    <span>失物图：</span>
                                    {
                                        imgs.map((item) => {
                                            return (
                                                <img
                                                    className='thingImage'
                                                    src={`${BaseUrl}${item}`}
                                                    alt=''
                                                    onClick={() => {
                                                        this.setState({
                                                            previewVisible: true,
                                                            previewImage: `${BaseUrl}${item}`
                                                        })
                                                    }}
                                                    style={{marginRight:'10px',borderRadius:'5px',border:'1px solid white'}}
                                                />
                                            )
                                        })
                                    }
                                </li>
                                <li>
                                    <span>失物描述：</span>{`${detail?.content}`}
                                </li>
                                <li >
                                    <span>发布时间：</span>{`${formatDate(detail?.createTime)}  (${getDateDiff(detail?.createTime)})`}
                                </li>
                                <li >
                                    <span>校区：</span>{`${detail?.campus}`}
                                </li>
                                <li>
                                    <span>发布者：</span>
                                    <img src={`${BaseUrl}${detail?.senderHead}`} alt="" style={{
                                        width: 48,
                                        height: 48,
                                        border: 'none',
                                        borderRadius: '50%',
                                        display: 'inline-block'
                                    }}
                                    />
                                    <div style={{ display: 'inline-block' }}>
                                        {detail?.senderNickName}
                                        {/* (ID:{detail?.senderId}) */}
                                    </div>
                                </li>
                                <li>
                                    <span>发现地点：</span>{`${detail?.findPlace}`}
                                </li>
                                <li>
                                    <span>发现时间：</span>{`${detail?.findTime}`}
                                </li>
                                <li>
                                    <span>物品类型：</span>{`${detail?.tag}`}
                                </li>
                            </ul>
                        </div>
                        {
                            type == 1 && <div className='getThing-box'>
                            <div className='getThing-text-1'>我要认领</div>
                            {
                                questions?.length>0?
                                <div className='getThing-text-2'>{hasAnswered?'您已回答，以下是您的答案：':'请回答认领问题：'}</div>:
                                <div className='getThing-text-2'>发布者未设置认领问题，发布者UID为{detail?.senderId}，您可在左下角聊天框内搜索该用户</div>
                            }
                            <ul style={{padding:'0 24px'}}>
                                {
                                    questions?.map((item,index)=>{
                                        return (
                                            <li style={{margin:'10px 0'}}>
                                                {`问题${index+1}：${item}`}
                                                <Input style={{width:'70%',display:'block',marginLeft:'6%',borderRadius:12,marginTop:6}} 
                                                placeholder={'请输入问题答案' }
                                                value={this.state.answers[index]}
                                                onChange={e=>{
                                                    let {answers} = this.state
                                                    answers[index] = e.target.value
                                                    this.setState({
                                                        answers
                                                    })
                                                }}/>
                                            </li>
                                        )
                                    })
                                }
                                {
                                    !hasAnswered && questions?.length>0 && <Button 
                                                        type="primary" 
                                                        block 
                                                        style={{borderRadius:16,marginTop:34}}
                                                        onClick={this.createOrder.bind(this)}
                                                    >
                                                        认领
                                                    </Button>
                                }
                            </ul>
                        </div>
                        }
                    </div>
                    <Modal
                        visible={previewVisible}
                        title='预览图片'
                        footer={null}
                        onCancel={() => {
                            this.setState({
                                previewVisible: false
                            })
                        }}
                    >
                        <img alt="example" style={{ width: '100%', border: 'none' }} src={previewImage} />
                    </Modal>
                </div>
            </Spin>
        )
    }
}
export default memo(thingDetail)